package com.qiniuyun.graph.common.component;


import com.qiniuyun.graph.common.entity.Users;
import com.qiniuyun.graph.common.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Ip 盐值 鉴权管理
 * Created by guxiang on 2020/3/13
 *
 * @author guxiang
 * @version 1.0
 * 2020/3/13
 */
@Service
public class IpSaltAuthenticationService {
    @Autowired
    private CacheService cacheService;

    public void auth(HttpServletRequest request) {
        String token = getToken(request);
        if (!StringUtils.isEmpty(token)) {
            Authentication authentication = getAuthentication(token);
            if (authentication != null) {
                SecurityContextHolder.getContext()
                        .setAuthentication(authentication);
            }
        }
    }

    /**
     * 获取授权
     *
     * @return
     */
    private Authentication getAuthentication(String token) {
        List<GrantedAuthority> auths = new ArrayList<>();
        auths.add(new SimpleGrantedAuthority("ROLE_USER"));
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(token, null, auths);
        return authentication;
    }

    /**
     * 生成系统用户
     *
     * @return
     */
    private static Users buildUser(Map<String, String> map) {
        Users users = new Users();
        users.setUsername(map.get("username"));
        users.setPassword(map.get("password"));
        return users;
    }

    /**
     * 获取缓存中的token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(token)) {
            token = token.replaceAll("Bearer", "").trim();
            if (cacheService.exists(token)) {
                return token;
            }
        }
        return null;
    }
}
